package com.jichangxiu.utils.maven;

import org.apache.maven.shared.invoker.*;

import java.io.File;
import java.util.Collections;
import java.util.Objects;

public class MavenUtils {

    private static final String MAVEN_HOME_PATH = Objects.requireNonNull(MavenUtils.class.getClassLoader().getResource("maven")).getPath();

    public static Boolean doClean(String path) {
        return execute("clean", path);
    }

    public static Boolean doValidate(String path) {
        return execute("validate", path);
    }

    public static Boolean doCompile(String path) {
        return execute("compile", path);
    }

    public static Boolean doTest(String path) {
        return execute("test", path);
    }

    public static Boolean doPackage(String path) {
        return execute("package", path);
    }

    public static Boolean doVerify(String path) {
        return execute("verify", path);
    }

    public static Boolean doInstall(String path) {
        return execute("install", path);
    }

    public static Boolean doSite(String path) {
        return execute("site", path);
    }

    public static Boolean doDeploy(String path) {
        return execute("deploy", path);
    }

    private static Boolean execute(String cmd, String path) {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setPomFile(new File(path));
        request.setGoals(Collections.singletonList(cmd));
        Invoker invoker = new DefaultInvoker();
        try {
            invoker.setMavenHome(new File(MAVEN_HOME_PATH));
            InvocationResult result = invoker.execute(request);
            int exitCode = result.getExitCode();
            return 0 == exitCode;
        } catch (MavenInvocationException e) {
            e.printStackTrace();
        }
        return false;
    }

}
